package com.atguigu.tingshu.user.api;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.annotation.GuiGuLogin;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 微信登录
     * @param code
     * @return
     */
    @GetMapping("/wxLogin/{code}")
    public Result<Map<String,String>> wxLogin(@PathVariable String code){
        String token = userInfoService.wxLogin(code);
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        return Result.ok(map);
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getUserInfo")
    @GuiGuLogin
    public Result<UserInfoVo> getUserInfo(){
        UserInfoVo userInfoVo = userInfoService.getUserInfo();
        return Result.ok(userInfoVo);
    }

    // /api/user/wxLogin/updateUser
    @PostMapping("/updateUser")
    @GuiGuLogin
    public Result updateUser(@RequestBody UserInfoVo userInfoVo, @RequestHeader("token") String token){

        //根据token获取用户信息
        String s = redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        UserInfo userInfo = JSON.parseObject(s, UserInfo.class);

//        BeanUtils.copyProperties(userInfoVo,userInfo);
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        //修改数据库表中的用户信息
        userInfoService.updateById(userInfo);

        //修改redis中的用户信息
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token,JSON.toJSONString(userInfo),7, TimeUnit.DAYS);
        return Result.ok();
    }
}
